<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>表单验证</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-size: 14px;
    }

    body {
      font-family: 宋体, sans-serif;
      background-color: #f4f4f4;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }

    .form-container {
      background-color: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      max-width: 400px;
      width: 100%;
    }

    .form-group {
      margin-bottom: 20px;
    }

    label {
      display: block;
      font-weight: bold;
      margin-bottom: 5px;
    }

    input[type="text"],
    input[type="password"] {
      width: 100%;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 4px;
      transition: border-color 0.3s;
    }

    input[type="text"]:focus,
    input[type="password"]:focus {
      outline: none;
      border-color: #007bff;
    }

    .error {
      font-size: 12px;
      color: #ff0000;
    }

    .success {
      font-size: 12px;
      color: #00ff00;
    }

    .form-group span {
      display: block;
      margin-top: 5px;
    }

    button {
      width: 100%;
      padding: 10px;
      border: none;
      border-radius: 4px;
      background-color: #007bff;
      color: white;
      cursor: pointer;
      transition: background-color 0.3s;
    }

    button:hover {
      background-color: #0056b3;
    }

    #successMessage {
      display: none;
      margin-top: 10px;
      font-weight: bold;
      color: #008000;
    }

    #dataTableContainer {
      margin-top: 20px;
    }

    #dataTableContainer table {
      width: 100%;
      border-collapse: collapse;
    }

    #dataTableContainer table,
    #dataTableContainer th,
    #dataTableContainer td {
      border: 1px solid #ccc;
      padding: 8px;
      text-align: left;
    }

    #dataTableContainer th {
      background-color: #f2f2f2;
    }
  </style>
</head>
<body>
  <div class="form-container" id="formContainer">
    <form id="userForm" method="post">
      <div class="form-group">
        <label for="username">用户名：</label>
        <input type="text" id="username" name="username" />
        <span id="usernameError" class="error"></span>
      </div>

      <div class="form-group">
        <label for="password">密码：</label>
        <input type="password" id="password" name="password" />
        <span id="passwordError" class="error"></span>
      </div>

      <div class="form-group">
        <label for="confirmPwd">确认密码：</label>
        <input type="password" id="confirmPwd" name="confirmPwd" />
        <span id="confirmPwdError" class="error"></span>
      </div>

      <div class="form-group">
        <label for="email">邮箱地址：</label>
        <input type="text" id="email" name="email" />
        <span id="emailError" class="error"></span>
      </div>

      <div class="form-group">
        <label for="idNumber">身份证号码：</label>
        <input type="text" id="idNumber" name="idNumber" />
        <span id="idNumberError" class="error"></span>
      </div>

      <div class="form-group">
        <label for="captcha">验证码：</label>
        <input type="text" id="captcha" name="captcha" />
        <span id="captchaError" class="error"></span>
      </div>

      <div class="form-group">
        <button type="button" id="submitBtn">提交信息</button>
        <span></span>
        <button type="reset" id="resetBtn">重置信息</button>
      </div>
    </form>
  </div>

  <div id="successMessage">表单验证通过，可以提交！</div>

  <div id="dataTableContainer"></div>

  <script>
    document.addEventListener("DOMContentLoaded", function () {
      function validateField(input, errorSpan, regex, errorMsg) {
        const value = input.value.trim();
        if (!value) {
          errorSpan.textContent = errorMsg;
          return false;
        }
        if (regex.test(value)) {
          errorSpan.textContent = "";
          return true;
        } else {
          errorSpan.textContent = errorMsg;
          return false;
        }
      }

      // 验证规则定义
      const validationRules = {
        username: {
          input: document.getElementById("username"),
          error: document.getElementById("usernameError"),
          regex: /^[a-zA-Z0-9_-]{4,16}$/,
          errorMsg: "用户名必须在4-16位，且只能包含字母、数字、下划线和短横线",
        },
        password: {
          input: document.getElementById("password"),
          error: document.getElementById("passwordError"),
          regex: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,18}$/,
          errorMsg: "密码必须是6-18位，且包含字母和数字",
        },
        confirmPwd: {
          input: document.getElementById("confirmPwd"),
          error: document.getElementById("confirmPwdError"),
          errorMsg: "确认密码与密码不匹配",
        },
        email: {
          input: document.getElementById("email"),
          error: document.getElementById("emailError"),
          regex: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
          errorMsg: "邮箱地址格式不正确",
        },
        idNumber: {
          input: document.getElementById("idNumber"),
          error: document.getElementById("idNumberError"),
          regex: /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])\d{3}[\dxX]$/,
          errorMsg: "身份证号码格式不正确",
        },
        captcha: {
          input: document.getElementById("captcha"),
          error: document.getElementById("captchaError"),
          regex: /^\d{6}$/,
          errorMsg: "验证码格式不正确",
        },
      };

      // 提交表单
      document.getElementById("submitBtn").addEventListener("click", function () {
        let isValid = true;

        // 遍历执行标准验证逻辑
        for (const key in validationRules) {
          const rule = validationRules[key];
          if (key !== "confirmPwd") { // 确认密码单独处理
            isValid &= validateField(rule.input, rule.error, rule.regex, rule.errorMsg);
          }
        }

        // 特殊处理确认密码验证
        const pwd = validationRules.password.input.value;
        const confirmPwd = validationRules.confirmPwd.input.value;
        if (pwd !== confirmPwd) {
          validationRules.confirmPwd.error.textContent = validationRules.confirmPwd.errorMsg;
          isValid = false;
        } else {
          validationRules.confirmPwd.error.textContent = ""; // 匹配时清除错误信息
        }

        if (isValid) {
          document.getElementById("formContainer").style.display = "none"; // 隐藏表单
          document.getElementById("successMessage").style.display = "block"; // 显示成功消息

          // 收集并展示数据
          const formData = {
            username: validationRules.username.input.value,
            email: validationRules.email.input.value,
            idNumber: validationRules.idNumber.input.value,
            captcha: validationRules.captcha.input.value,
          };

          const tableContainer = document.getElementById("dataTableContainer");
          const table = document.createElement("table");
          const tbody = document.createElement("tbody");

          // 创建表头
          const thead = document.createElement("thead");
          const headRow = document.createElement("tr");
          for (const key in formData) {
            const th = document.createElement("th");
            th.textContent = key;
            headRow.appendChild(th);
          }
          thead.appendChild(headRow);
          table.appendChild(thead);

          // 创建表格内容
          const dataRow = document.createElement("tr");
          for (const key in formData) {
            const td = document.createElement("td");
            td.textContent = formData[key];
            dataRow.appendChild(td);
          }
          tbody.appendChild(dataRow);
          table.appendChild(tbody);

          tableContainer.innerHTML = ""; // 清空容器
          tableContainer.appendChild(table);

          console.log("表单验证通过，可以提交!");
        }
      });
    });
  </script>
</body>
</html>
